package licode.unisop.auth.infrastructure.service;

import licode.unisop.auth.application.gateway.StrategyAuthGateway;
import licode.unisop.auth.client.info.StrategyContext;
import licode.unisop.auth.exception.AuthErrorCode;
import licode.unisop.oidc.auth.api.OidcSession;
import licode.unisop.oidc.auth.modal.LoginId;
import licode.unisop.oidc.auth.modal.UserInfoId;
import licode.unisop.oidc.auth.stu.AuthorUtil;
import licode.unisop.platform.client.api.SiPlatformAuthService;
import licode.unisop.platform.client.api.SiPlatformQueryService;
import licode.unisop.provider.vo.SiProps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 执行登录的策略检测
 *
 * @author licode
 */
@Component
public class StrategyAuthGatewayDefault implements StrategyAuthGateway {
    @Resource
    private SiPlatformAuthService siPlatformAuthService;

    @Override
    public void checkStrategy(StrategyContext context) {
        UserInfoId infoId;
        boolean singleLogin = false;
        List<String> terminals = null;
        if (null != context.getPlatform()) {
            SiProps props = context.getPlatform().getProps();
            infoId = UserInfoId.build(context.getRealmId(), context.getUserId());
            OidcSession session = AuthorUtil.getSession(infoId);

            if (null != session) {
                String pid = context.getPlatform().getId();
                String tid = context.getTerminalId();

                if (null != props) {
                    String terminalCodes = props.getString("$singleLoginTerminals", "");
                    singleLogin = props.getBool("$singleLogin", singleLogin);
                    terminals = Arrays.asList(terminalCodes.split(","));
                }

                if (singleLogin) {
                    session.tickOffTerminalLogin(pid, tid);
                } else if (terminals != null && !terminals.isEmpty() && null != tid) {
                    if (terminals.contains(tid)) {
                        session.tickOffTerminalLogin(pid, tid);
                    }
                }
            }
        }
    }
}
